package huaxin.controller;

import huaxin.domain.CommonResult;
import huaxin.domain.Order;
import huaxin.service.AccountService;
import huaxin.service.OrderService;
import huaxin.service.StorageService;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.security.PublicKey;

/**
 * created by king on 2020/6/3 10:48 下午
 */
@RestController
@Slf4j
public class OrderController {
    @Resource
    private OrderService orderService;

    @Resource
    private StorageService storageService;

    @Resource
    private AccountService accountService;

    /**
     * 单独测试事务是否生效
     * @return
     */
    @GetMapping("/test")
    @GlobalTransactional
    public String test() {
        Order order = new Order();
        order.setUserId(1L);
        order.setCount(10);
        order.setMoney(BigDecimal.valueOf(111));
        order.setProductId(1L);
        //orderService.create(order);
        System.err.println(RootContext.getXID());
        //int i = 10 / 0;
        return "true";
    }

    /**
     * 测试分布式事务,    * 创建订单->调用库存服务扣减库存->调用账户服务扣减账户余额->修改订单状态
     *      * 简单说：下订单->扣库存->减余额->改状态
     * @param order
     * @return
     * @throws TransactionException
     */
    @GetMapping("/order/create")
    @GlobalTransactional
    public CommonResult create(Order order) throws TransactionException {
        System.err.println(("seata分布式事务Id:{}" + RootContext.getXID()));
        //1 新建订单
        orderService.create(order);

        //2 扣减库存
        log.info("----->订单微服务开始调用库存，做扣减Count");
        storageService.decreaseStorage(order.getProductId(), order.getCount());
        log.info("----->订单微服务开始调用库存，做扣减end");

        //3 扣减账户
        log.info("----->订单微服务开始调用账户，做扣减Money");
        accountService.decreaseAccount(order.getUserId(), order.getMoney());
        log.info("----->订单微服务开始调用账户，做扣减end");

        //4修改订单状态，从零到1,1代表已经完成
        orderService.update(order.getUserId(), 1);

        log.info("----->下订单结束了，O(∩_∩)O哈哈~");

        return new CommonResult(200, "订单创建成功");
    }
}
